package com.minio.oss.http;

import com.minio.oss.service.OssProperties;
import com.minio.oss.service.OssTemplate;
import com.utility.result.Result;
import com.utility.util.UnitConvertUtil;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 文件上传
 *
 * @author zhousl
 * @date 2020/11/4 10:59
 */
@RestController
@AllArgsConstructor
@RequestMapping("/api/system/oss")
public class UploadController {

    private final OssProperties ossProperties;

    private final OssTemplate minioTemplate;

    /**
     * 上传文件 文件名采用uuid,避免原始文件名中带"-"符号导致下载的时候解析出现异常
     *
     * @param file 资源
     * @return R(/ admin / bucketName / filename)
     */

    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file) {
        //todo 文件名要处理下
        String fileName = UUID.randomUUID().toString().replaceAll("-","") + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        Map<String, String> resultMap = new HashMap<>(4);
        resultMap.put("bucketName", ossProperties.getBucketName());
        resultMap.put("fileName", file.getOriginalFilename());
        resultMap.put("filePostfix", fileName.substring(fileName.lastIndexOf(".") + 1));
        resultMap.put("fileSize", UnitConvertUtil.readableFileSize(file.getSize()));
        resultMap.put("url", String.format("%s/%s/%s",ossProperties.getReturnUrl(), ossProperties.getBucketName(), fileName));

        try {
            minioTemplate.putObject(ossProperties.getBucketName(), fileName, file.getInputStream());
        } catch (Exception e) {
            return Result.returnCodeError(e.getLocalizedMessage());
        }
        return Result.returnCodeSuccess(resultMap);
    }



    /**
     * 删除文件
     *
     * @param fileName 文件名称
     * @see <a href= "http://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObject">AWS API Documentation</a>
     */
    @GetMapping("/remove")
    public Result remove(@RequestParam(value = "fileName")String fileName) throws Exception {
        String[] wdlns = fileName.substring(fileName.indexOf("wdln")).split("/");
        minioTemplate.removeObject(ossProperties.getBucketName(),wdlns[1]);
        return Result.returnCodeSuccess();
    }
}
